package com.bawei.module_mall

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.module_mall.adapter.ShopAdapter
import com.bawei.module_mall.databinding.ActivityShopBinding
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.http.viewModel.ShopViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import androidx.appcompat.app.AlertDialog
import com.bawei.module_mall.model.AddShopModel
import com.bawei.module_mall.model.DeleteModel
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.ImageView
import com.google.android.material.bottomsheet.BottomSheetDialog
import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import retrofit2.HttpException
import kotlinx.coroutines.CancellationException

@Route(path = Router.Ui.SHOP_ACTIVITY)
    class ShopActivity : BaseActivity() {

        private val binding by lazy { ActivityShopBinding.inflate(layoutInflater) }
        private val viewModel: ShopViewModel by viewModels()
        private lateinit var adapter: ShopAdapter
        private val selectedIds = mutableSetOf<Int>() // 本地保存选中商品id

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        adapter = ShopAdapter(mutableListOf(),
            onCountChange = { item, action ->
                when (action) {
                    "plus" -> {
                        lifecycleScope.launch {
                            try {
                                val addShopModel = AddShopModel(
                                    goodsCode = "",
                                    goodsId = item.goodsId,
                                    goodsName = item.goodsName,
                                    goodsSkuCode = item.goodsSkuCode,
                                    goodsSkuId = item.goodsSkuId,
                                    goodsSkuName = item.goodsSkuName,
                                    number = 1
                                )
                                viewModel.intents.send(ShopIntent.AddShop(addShopModel))
                                selectedIds.add(item.id) // 保证加减后仍然选中
                                selectedIds.clear()
                                selectedIds.addAll(adapter.getSelectedItems().map { it.id })
                            } catch (e: HttpException) {
                                if (e.code() == 999) {
                                    Toast.makeText(this@ShopActivity, "服务器响应异常，请联系管理员", Toast.LENGTH_LONG).show()
                                } else {
                                    Toast.makeText(this@ShopActivity, "网络请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                                }
                            } catch (e: Exception) {
                                if (e is CancellationException) return@launch
                                Toast.makeText(this@ShopActivity, "未知错误: ${e.message}", Toast.LENGTH_LONG).show()
                            }
                        }
                    }
                    "minus" -> {
                        lifecycleScope.launch {
                            try {
                                val addShopModel = AddShopModel(
                                    goodsCode = "",
                                    goodsId = item.goodsId,
                                    goodsName = item.goodsName,
                                    goodsSkuCode = item.goodsSkuCode,
                                    goodsSkuId = item.goodsSkuId,
                                    goodsSkuName = item.goodsSkuName,
                                    number = -1
                                )
                                viewModel.intents.send(ShopIntent.AddShop(addShopModel))
                                selectedIds.add(item.id) // 保证加减后仍然选中
                                selectedIds.clear()
                                selectedIds.addAll(adapter.getSelectedItems().map { it.id })
                            } catch (e: HttpException) {
                                if (e.code() == 999) {
                                    Toast.makeText(this@ShopActivity, "服务器响应异常，请联系管理员", Toast.LENGTH_LONG).show()
                                } else {
                                    Toast.makeText(this@ShopActivity, "网络请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                                }
                            } catch (e: Exception) {
                                if (e is CancellationException) return@launch
                                Toast.makeText(this@ShopActivity, "未知错误: ${e.message}", Toast.LENGTH_LONG).show()
                            }
                        }
                    }
                    "delete_confirm" -> {
                        AlertDialog.Builder(this)
                            .setMessage("确定要删除该商品吗？")
                            .setPositiveButton("确定") { _, _ ->
                                lifecycleScope.launch {
                                    try {
                                        val deleteModel = DeleteModel(
                                            carId = item.id.toString()
                                        )
                                        viewModel.intents.send(ShopIntent.DeleteShop(deleteModel))
                                    } catch (e: HttpException) {
                                        if (e.code() == 999) {
                                            Toast.makeText(this@ShopActivity, "服务器响应异常，请联系管理员", Toast.LENGTH_LONG).show()
                                        } else {
                                            Toast.makeText(this@ShopActivity, "网络请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                                        }
                                    } catch (e: Exception) {
                                        if (e is CancellationException) return@launch
                                        Toast.makeText(this@ShopActivity, "未知错误: ${e.message}", Toast.LENGTH_LONG).show()
                                    }
                                }
                            }
                            .setNegativeButton("取消", null)
                            .show()
                    }
                }
            },
            onCheckedChange = { item, checked ->
                item.isChecked = checked
                adapter.updateItem(item)
                if (checked) {
                    selectedIds.add(item.id)
                } else {
                    selectedIds.remove(item.id)
                }
                // 临时移除监听，防止递归
                binding.checkboxSelectAll.setOnCheckedChangeListener(null)
                binding.checkboxSelectAll.isChecked = adapter.getAllChecked()
                // 恢复监听（不要重复完整逻辑）
                binding.checkboxSelectAll.setOnCheckedChangeListener { _, isChecked ->
                    adapter.setAllChecked(isChecked)
                    if (isChecked) {
                        selectedIds.clear()
//                        selectedIds.addAll(adapter.getItems().map { it.id })
                    } else {
                        selectedIds.clear()
                    }
                    updateTotalAndSelectAll()
                }
                updateTotalAndSelectAll()
            },
            onCollectClick = { item ->
                lifecycleScope.launch {
                    try {
                        // 直接切换收藏状态，让主状态监听器处理结果
                        viewModel.intents.send(ShopIntent.ToggleCollect(item.goodsId))
                    } catch (e: Exception) {
                        if (e is CancellationException) return@launch
                        Toast.makeText(this@ShopActivity, "收藏操作失败: ${e.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        )
        binding.imgBack.setOnClickListener {
            finish()
        }
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter
        // 全选CheckBox监听（只保留这一处）
        binding.checkboxSelectAll.setOnCheckedChangeListener { _, isChecked ->
            adapter.setAllChecked(isChecked)
            if (isChecked) {
                selectedIds.clear()
//                selectedIds.addAll(adapter.getItems().map { it.id })
            } else {
                selectedIds.clear()
            }
            updateTotalAndSelectAll()
        }
        // 拉取购物车数据
        lifecycleScope.launch {
            try {
                viewModel.intents.send(ShopIntent.GetShop)
            } catch (e: HttpException) {
                if (e.code() == 999) {
                    Toast.makeText(this@ShopActivity, "服务器响应异常，请联系管理员", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this@ShopActivity, "网络请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
            } catch (e: Exception) {
                if (e is CancellationException) return@launch
                Toast.makeText(this@ShopActivity, "未知错误: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
        // 监听数据流
        lifecycleScope.launch {
            try {
                viewModel.state.collectLatest { state ->
                    when (state) {
                        is ShopState.GetShopSuccess -> {
                            val list = state.data?.items ?: emptyList()
                            // 恢复本地选中状态
                            list.forEach { it.isChecked = selectedIds.contains(it.id) }
                            adapter.setData(list)
                            // 数据刷新后，联动全选和总价
                            binding.checkboxSelectAll.isChecked = adapter.getAllChecked()
                            updateTotalAndSelectAll()
                        }
                        is ShopState.CheckCollectResult -> {
                            // 更新对应商品的收藏状态
                            val item = adapter.getItems().find { it.goodsId == state.goodsId }
                            item?.let {
                                it.isCollected = state.isCollected
                                adapter.updateItem(it)
                                Toast.makeText(this@ShopActivity, if (state.isCollected) "已收藏" else "已取消收藏", Toast.LENGTH_SHORT).show()
                            }
                        }
                        is ShopState.Error -> {
                            Toast.makeText(this@ShopActivity, state.error, Toast.LENGTH_SHORT).show()
                        }
                        else -> {}
                    }
                }
            } catch (e: HttpException) {
                if (e.code() == 999) {
                    Toast.makeText(this@ShopActivity, "服务器响应异常，请联系管理员", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this@ShopActivity, "网络请求失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
            } catch (e: Exception) {
                if (e is CancellationException) return@launch
                Toast.makeText(this@ShopActivity, "未知错误: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
        binding.btnCheckout.setOnClickListener {
            val selectedItems = adapter.getSelectedItems()
            if (selectedItems.isNotEmpty()) {
                val item = selectedItems[0]
                // 这里假设item有goodsName、goodsDesc、price、number、skuImgUrl等字段
                ARouter.getInstance()
                    .build("/module_shop/OrderSheetActivity")
                    .withString("goodsName", item.goodsName)
                    .withString("goodsDesc", item.goodsSkuName)
                    .withDouble("goodsPrice", item.price.toDouble())
                    .withInt("goodsCount", item.number)
                    .withString("goodsImg", item.mainImageUrl)
                    .navigation()
            } else {
                Toast.makeText(this, "请选择商品", Toast.LENGTH_SHORT).show()
            }
        }
        // 明细弹窗
        binding.tvDetail.setOnClickListener {
            val dialog = BottomSheetDialog(this)
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_price_detail, null)
            val tvTotal = view.findViewById<TextView>(R.id.tv_price_total)
            val tvDiscount = view.findViewById<TextView>(R.id.tv_price_discount)
            val ivClose = view.findViewById<ImageView>(R.id.iv_close)
            // 计算选中商品总额
            val selectedItems = adapter.getSelectedItems()
            val total = selectedItems.sumOf { it.price * it.number }
            tvTotal.text = "￥$total"
            tvDiscount.text = "￥0" // 这里可根据实际优惠逻辑修改
            ivClose.setOnClickListener { dialog.dismiss() }
            dialog.setContentView(view)
            dialog.show()
        }
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    // 联动总价和全选
    private fun updateTotalAndSelectAll() {
        val selectedItems = adapter.getSelectedItems()
        val total = selectedItems.sumOf { it.price * it.number }
        val selectedKinds = selectedItems.size // 选中商品种类数
        val selectedCount = selectedItems.sumOf { it.number } // 选中商品总件数

        binding.tvTotalPrice.text = "￥$total"
        binding.checkboxSelectAll.isChecked = adapter.getAllChecked()

        // “全部”后面显示选中种类数
        binding.tabAll.text = if (selectedKinds > 0) "全部($selectedKinds)" else "全部"
        // “去结算”按钮显示选中商品总件数，数字为白色
        if (selectedCount > 0) {
            val btnText = "去结算($selectedCount)"
            val spannable = SpannableString(btnText)
            val color = ContextCompat.getColor(this, android.R.color.white)
            val start = btnText.indexOf('(')
            val end = btnText.indexOf(')') + 1
            if (start in 0 until end) {
                spannable.setSpan(
                    ForegroundColorSpan(color),
                    start,
                    end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
            binding.btnCheckout.text = spannable
        } else {
            binding.btnCheckout.text = "去结算"
        }
    }
}